﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using ATTools.Models;
using ATTools.Services;
using ATTools.ViewModels;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.Media.Services;

namespace ATTools.Drivers
{
    [OrchardFeature("ATTools")]
    public class SoundDriver : ContentPartDriver<SoundPart> 
    {

        private readonly IMediaService _mediaService;
        private readonly ISpeakService _speakService;
        private readonly ITranslationService _translationService;

        public Localizer T { get; set; }

        public SoundDriver(IMediaService mediaService, ISpeakService speakService, ITranslationService translationService)
        {
            _mediaService = mediaService;
            _speakService = speakService;
            _translationService = translationService;

            T = NullLocalizer.Instance;
        }


        protected override DriverResult Display(SoundPart part, string displayType, dynamic shapeHelper)
        {

            return ContentShape("Parts_Sound", () => shapeHelper.Parts_Sound(
                part
                ));
        }

        //GET
        protected override DriverResult Editor(SoundPart part, dynamic shapeHelper)
        {
            //The available languages for generation of sound file
            IEnumerable<string> aVoices = _speakService.GetAvailableLanguages();
            IEnumerable<string> voiceNames = _translationService.GetLanguageNames(aVoices.ToArray());

            List<Voice> voices = new List<Voice>();
            voices.Add(new Voice() { Name = "Auto detect", FriendlyName = T("Auto detect").ToString() });
            
            for (int i = 0; i < aVoices.Count(); i++)
            {
                Voice voice = new Voice()
                {
                    Name = aVoices.ElementAt(i),
                    FriendlyName = voiceNames.ElementAt(i)
                };
                voices.Add(voice);
            }

            var model = new SoundPartViewModel
            {
                Part = part,
                AvailableLanguages = voices
            };


            return ContentShape("Parts_Sound_Edit",
                () => shapeHelper.EditorTemplate(
                    TemplateName: "Parts/Sound",
                    Model: model,
                    Prefix: Prefix));
        }

        //POST
        protected override DriverResult Editor(SoundPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            //Get the custom sound, save it and use it as the sound
            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                var postedFile = ((Controller)updater).Request.Files["SoundUploadField"];

                var mediaFolder = "ATTools-CustomSounds";
                if (postedFile != null && postedFile.ContentLength != 0)
                {

                    if (_mediaService.FileAllowed(postedFile))
                    {
                        var postedFileLength = postedFile.ContentLength;
                        var postedFileStream = postedFile.InputStream;
                        var postedFileData = new byte[postedFileLength];
                        var postedFileName = Path.GetFileName(postedFile.FileName);
                        postedFileStream.Read(postedFileData, 0, postedFileLength);

                        string uploadedFileName = String.Empty;

                        string uniqueFileName = postedFileName;

                        try
                        {
                            _mediaService.CreateFolder(null, mediaFolder);
                        }
                        catch
                        {
                            ;
                        }

                        var existingFiles = _mediaService.GetMediaFiles(mediaFolder);
                        bool found = true;
                        var index = 0;
                        while (found)
                        {
                            index++;
                            uniqueFileName = String.Format("{0}-{1}{2}", Path.GetFileNameWithoutExtension(postedFileName), index, Path.GetExtension(postedFileName));
                            found = existingFiles.Any(f => 0 == String.Compare(uniqueFileName, f.Name, StringComparison.OrdinalIgnoreCase));
                        }

                        uploadedFileName = _mediaService.UploadMediaFile(mediaFolder, uniqueFileName, postedFileData, false);

                        part.CustomSoundString = uploadedFileName;
                    }
                    else
                    {
                        updater.AddModelError("File", T("The file type is not allowed for: {0}.", postedFile.FileName));
                    }
                }

            }
            
            return Editor(part, shapeHelper);
        }

    }

    
}